import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/404.dart';
import 'package:flutter_enjoy_plus/pages/house/house_list.dart';
import 'package:flutter_enjoy_plus/pages/house/location_list.dart';
import 'package:flutter_enjoy_plus/pages/login/index.dart';
import 'package:flutter_enjoy_plus/pages/notice/index.dart';
import 'package:flutter_enjoy_plus/pages/profile/index.dart';
import 'package:flutter_enjoy_plus/pages/tabs_page.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

void main() {
  runApp(MaterialApp(
    routes: {
      '/': (context) => const TabsPage(),
      '/notice_detail': (context) => const NoticeDetail(),
      '/login': (context) => const LoginPage(),
      // '/profile': (context) => const ProfilePage(),
    },
    // 默认启动页面
    initialRoute: '/',
    // 路由拦截 - pushNamed 进行跳转时 && 访问的页面路径并不是上方routes中所定义
    onGenerateRoute: (setting) {
      // setting 路由对象 setting.name 路由的名称 / setting.arguments 路由的参数
      // 获取token 判断token是否存在
      final token = tokenManager.getToken();
      if (token.isEmpty) {
        // 如果token不存在 跳转至登录页面
        return MaterialPageRoute(builder: (context) => const LoginPage());
      } else {
        if (setting.name == '/profile') {
          // 直接放行
          return MaterialPageRoute(
              builder: (context) => ProfilePage(
                    userInfo: setting.arguments as Map<String, dynamic>,
                  ));
        }
        if (setting.name == '/house') {
          return MaterialPageRoute(builder: (context) => const HouseList());
        }
        if (setting.name == '/add_house') {
          return MaterialPageRoute(builder: (context) => const LocationList());
        }
      }
      // 什么都不做
      return MaterialPageRoute(builder: (context) => const NotFound());
    },
  ));
}
